import gi, time
gi.require_version("Gtk", "4.0")
from gi.repository import Gtk, GLib, GObject

class MyWindow(Gtk.ApplicationWindow):
    @GObject.Signal(
        name="thread-message",
        flags=GObject.SignalFlags.RUN_LAST,
        return_type=GObject.TYPE_NONE,
        arg_types=(str,)
    )
    def on_thread_message(self, message):
        print(f"Received message in main thread: {message}")
        if message == "Message 4":
            self.destroy()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.set_title("Thread Example")
        self.set_default_size(200, 100)

def worker_function(window):
    for i in range(5):
        # 模拟子线程发送消息
        GLib.idle_add(lambda: window.emit("thread-message", f"Message {i}"))
        time.sleep(1)

if __name__ == "__main__":
    app = Gtk.Application(application_id="com.example.ThreadApp")

    def on_activate(app):
        window = MyWindow(application=app)
        window.present()

        # 启动子线程
        import threading
        threading.Thread(target=worker_function, args=(window,), daemon=True).start()

    app.connect("activate", on_activate)
    app.run()